package com.example.springbootwebrestfulcrud.controller;

import com.example.springbootwebrestfulcrud.dao.DepartmentDao;
import com.example.springbootwebrestfulcrud.dao.EmployeeDao;
import com.example.springbootwebrestfulcrud.entities.Department;
import com.example.springbootwebrestfulcrud.entities.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * @Auther: luzhanshi
 * @Date: 2021/2/2 - 02 - 02 - 20:36 
 * @Description: com.example.springbootwebrestfulcrud.controller
 * @version: 1.0
 */
@Controller
public class EmployeeController {
    Logger logger = LoggerFactory.getLogger(EmployeeController.class);
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;

    /**
     * 查询所有 员工返回员工列表页面
     */
    @GetMapping("/emps")
    public String list(Model model) {
        /**
         * thymeleaf会自动拼接：
         * classpath:/templates/***.html
         */
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps", employees);
        return "emp/list";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/emp")
    public String emp(Model model) {
        //查出所有的部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
        return "emp/add";
    }

    /**
     * 添加员工
     * springMVC自动将请求参数和入参对象属性一一绑定；要求，请求参数名字和javabean里面的属性名是一样的
     */
    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        /**
         * 到员工列表页面
         * redirect：表示重定向到一个地址  /代表当前项目路径
         * forward：表示转发到一个地址
         */
        System.out.println("提交的员工信息：" + employee);
        //保存员工
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 跳转到修改员工信息页面
     */
    @GetMapping("/emp/{id}")
    public String toEdit(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeDao.get(id);
        //查出所有的部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
        model.addAttribute("emp", employee);
        //返回到修改页面
        return "emp/edit";
    }

    /**
     * 更新员工信息
     * @param employee
     * @return
     */
    @PutMapping("/emp")
    public String updateEmp(Employee employee) {
//        logger.info("更新的员工信息：=====" + employee);
        logger.debug("这是debug日志=============");
        employeeDao.save(employee);
        return "redirect:/emps";
    }
/**
 * 删除员工信息
 */
@DeleteMapping("/emp/{id}")
public String deleteEmp(@PathVariable("id") Integer id){
    employeeDao.delete(id);

    return "redirect:/emps";
}
}
